const fs = require('fs');
const path = require('path');
const logger = require('./util/logger');
const createSVG = require('./lib/createSVG');
const createTTF = require('./lib/createTTF');
const createEOT = require('./lib/createEOT');
const createWOFF = require('./lib/createWOFF');
const createCSS = require('./lib/createCSS');
const roots = process.cwd();  // 当前处于fonts文件夹里面
let isBreak = false; // 是否中止进程

// 检验重复名文件和非svg文件
let validFile = (filesArr) => {
  let validData = filesArr.reduce((obj, v) => {
    if (/\.svg$/i.test(v)) {
      let name = v.replace(/.*\/([^/]+)\.svg$/i, '$1');
      obj.nameData[name] = [].concat(obj[name] || [], v)
    } else if(!/\.DS_Store$/i.test(v)){ // .DS_Store是隐藏的系统文件
      obj.otherTypeFile.push(v);
    }
    return obj;
  }, { 
    otherTypeFile: [],
    nameData: {}
  });
  if (validData.otherTypeFile.length) {
    logger.warning('--下面不是svg文件，请移除：');
    validData.otherTypeFile.forEach(v => logger.warning(v));
  }
  Object.keys(validData.nameData).forEach(v => {
    if (validData.nameData[v].length > 1) {
      isBreak = true;
      logger.error('--重名文件，请按照规范修改文件名：');
      validData.nameData[v].forEach(v => logger.error(v))
    }
  });
  isBreak && process.exit(1);
}
const defaultOptions = {
  fontName: 'iconfont',
  baseClass: 'text-icon',
  classPrefix: 'icon-',
  files: path.join(roots, './svgs'), // 可以接受一个数组，或者一个路径
  output: path.join(roots, './font'),
  cssPath: path.join(roots, './font.css'),
  publicPath: null, // 当使用less的@import时，出现找不到字体文件时，可以手动传入相对路径
  unicodeStart: 57344,
  successLog: true, // 是否展示成功日志
  svgicons2svgfont: {}, // svgicons2svgfont插件的options
  svg2ttf: {}, // svg2ttf插件的options
};

module.exports = async function(options) {
  let opt = { ...defaultOptions, ...options };
  // 如果不展示成功日志，把logger.success置为空
  if (!opt.successLog) {
    logger.success = function() {};
  }
  try{
    // 如果入口文件是一个或多个字符串路径，获取到对应路径
    let filesArr = [];
    [].concat(opt.files).forEach(item => {
      if (typeof item === 'string') {
        if (!fs.existsSync(item)) {
          logger.error(`files字段目录不存在！（${item}）`);
          return;
        }
        let files = fs.readdirSync(item, 'utf-8');
        if (!files) {
          logger.error(`files字段目录是空的！（${item}）`)
        }
        filesArr = filesArr.concat(files.map(file => path.join(item, file)));
      }
    });
    isBreak && process.exit(1);

    // 判断是否有重复名称的svg图标
    validFile(filesArr);
    opt.files = filesArr;
    opt.svgPath = path.join(opt.output, opt.fontName + '.svg');
    opt.eotPath = path.join(opt.output, opt.fontName + '.eot');
    opt.ttfPath = path.join(opt.output, opt.fontName + '.ttf');
    opt.woffPath = path.join(opt.output, opt.fontName + '.woff');

    if (!fs.existsSync(opt.output)) {
      fs.mkdirSync(opt.output);
    }
    
    let glyphList = await createSVG(opt);
    logger.success('svgFont created successfully!');

    let ttfFont = createTTF(opt);
    logger.success('ttfFont created successfully!');

    createEOT(opt, ttfFont);
    logger.success('eotFont created successfully!');

    createWOFF(opt, ttfFont);
    logger.success('woffFont created successfully!');

    createCSS(opt, glyphList);
    logger.success('css created successfully!');
    logger.success('font created successfully!');
  }catch(e){
    logger.error(e);
  }
};
